package cn.sdormitory.common;

import cn.sdormitory.common.utils.SysUserUtils;
import com.baomidou.mybatisplus.annotation.TableId;
import lombok.Getter;

import java.util.Date;

@Getter
public class BaseEntity<Entity extends BaseEntity<Entity,Id>,Id> {
    @TableId
    private Id id;

    private String createBy;

    private Date createdTime;

    private String modifyBy;

    private Date modifyTime;

    public Entity setId(Id id) {
        this.id = id;
        //noinspection unchecked
        return (Entity) this;
    }

    public Entity setCreateBy(String createBy) {
        this.createBy = createBy;
        //noinspection unchecked
        return (Entity) this;
    }

    public Entity setCreatedTime(Date createdTime) {
        this.createdTime = createdTime;
        //noinspection unchecked
        return (Entity) this;
    }

    public Entity setModifyBy(String modifyBy) {
        this.modifyBy = modifyBy;
        //noinspection unchecked
        return (Entity) this;
    }

    public Entity setModifyTime(Date modifyTime) {
        this.modifyTime = modifyTime;
        //noinspection unchecked
        return (Entity) this;
    }

    public Entity initCreateAndModifyInfo(){
        // 防止子类覆盖不直接获取属性,调用get方法
        if(getId() == null){
            initCreateInfo();
        }else{
            initModifyInfo();
        }
        //noinspection unchecked
        return (Entity) this;
    }

    private void initModifyInfo() {
        setModifyBy(SysUserUtils.getSysUser().getUsername());
        setModifyTime(new Date());
    }

    private void initCreateInfo() {
        setCreateBy(SysUserUtils.getSysUser().getUsername());
        setCreatedTime(new Date());
    }
}
